package com.sgb.member.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.PoiItem;
import com.lxj.xpopup.util.KeyboardUtils;
import com.sgb.alimaplibrary.widget.MapMarkerView;
import com.sgb.member.R;
import com.sgb.member.databinding.ActivityMemberMapBinding;
import com.sgb.member.ui.adapter.MemberMapSearchAdapter;
import com.swgk.core.base.AppActivity;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.MToast;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 会员地址选择
 */
public class MemberMapActivity extends AppActivity {


    public static final String CURRENT_POSITION = "position";
    public static final String TITLE = "title";
    public static final String HINT = "hint";
    public static final String SAVE_TEXT = "savetext";
    public static final String CITY = "city";
    public static final String LATITUDE = "latitude";
    public static final String LONGTITUDE = "longtitude";
    public static final String ADDRESS = "address";
    public static final String SHOWLOCATION = "SHOWLOCATION";
    public static final String IS_FRAGMENT = "IS_FRAGMENT";

    private static final String TAG = "SelectAddressActivity";
    //默认选中经纬度
    private LatLng mFinalLatLng = new LatLng(0, 0);

    private int pos = 0;
    private String cityName = "";

    private String searchText = "";
    private boolean isSearching = false;
    private MemberMapSearchAdapter membermapsearchadapter;
    private boolean isHandSetting = false;
    private ActivityMemberMapBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView(savedInstanceState);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_member_map);
        binding.actionBar.ivBack.setOnClickListener(this);
        binding.searchPosition.setOnClickListener(this);
        binding.commitButton.setOnClickListener(this);
        binding.llButtomLayout.setOnClickListener(this);
        binding.tvSearchDelete.setOnClickListener(this);
    }

    @Override
    protected void init() {
        initData();
    }

    private void initView(Bundle savedInstanceState) {
        initMap(savedInstanceState);
        initPoiSearch();
    }

    private void initData() {
        if (getIntent() != null) {
            if (getIntent().hasExtra(TITLE)) {
                binding.actionBar.titleView.setText(getIntent().getStringExtra(TITLE));
                if ("地图详情".equals(TITLE)){
                    binding.llButtomLayout.setVisibility(View.GONE);
                    binding.commitButton.setVisibility(View.GONE);
                    binding.layoutSearch.setVisibility(View.GONE);
                }
            }

            if (getIntent().hasExtra(HINT)) {
                binding.searchAddress.setHint(getIntent().getStringExtra(HINT));
            } else {
                binding.searchAddress.setHint("请输入地址");
            }
            if (getIntent().hasExtra(SAVE_TEXT)) {
                binding.commitButton.setText(getIntent().getStringExtra(SAVE_TEXT));
            }

            if(getIntent().hasExtra(SHOWLOCATION)){

                binding.searchAddress.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if (isSearching) return true;
                        if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                            if (TextUtils.isEmpty(binding.searchAddress.getText().toString())) {
                                MToast.showToast(MemberMapActivity.this, "请输入搜索内容");
                                return true;
                            }
                            if (searchText.equals(binding.searchAddress.getText().toString())){
                                MToast.showToast(MemberMapActivity.this, "请输入不同的搜索内容");
                                return true;
                            }
                            isSearching = true;
                            searchText = binding.searchAddress.getText().toString().trim();
                            binding.mMapView.setPoiSearch(searchText, "");
                        }
                        return false;
                    }
                });

                binding.searchAddress.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        if(TextUtils.isEmpty(s)){
                            binding.tvSearchDelete.setVisibility(View.GONE);
                        }else{
                            binding.tvSearchDelete.setVisibility(View.VISIBLE);
                        }
                        if(!isHandSetting){
                            binding.mMapView.setPoiSearch(s.toString(), "");
                        }
                        binding.searchAddress.setSelection(s.length());
                    }

                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                    }
                });

                binding.searchList.addItemDecoration(new RecyclerCustomDecoration(0,
                        0,
                        0,
                        getResources().getDimension(R.dimen.dp1), getResources().getColor(R.color.color_main_bg)));
                binding.searchList.setLayoutManager(new LinearLayoutManager(this));

            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(getIntent().hasExtra(SHOWLOCATION)){
            binding.searchAddress.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
            binding.searchAddress.setFocusable(true);
            binding.searchAddress.setFocusableInTouchMode(true);
            binding.searchAddress.requestFocus();
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                               public void run() {
                                   InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                   imm.showSoftInput(binding.searchAddress, InputMethodManager.SHOW_FORCED);
                               }
                           },
                    1200);
        }
    }

    private void initMap(Bundle savedInstanceState) {
        binding.mMapView.initMap(savedInstanceState, getLifecycle(), new MapMarkerView.CallBack() {
            @Override
            public void onMarkerClick(int pos, String title) {
                showMarkerView(pos,title);
            }

            @Override
            public void onLocation(Double Lat, Double Log, String string) {
                if (mFinalLatLng.longitude != 0 && mFinalLatLng.latitude !=0) return;
                mFinalLatLng = new LatLng(Lat, Log);
                binding.currentPosition.setText(string);
//                binding.tvAddressName.setText("当前位置："+string);
            }

            @Override
            public void getAddress(Double Lat, Double Log,String string) {
                super.getAddress(Lat,Log,string);
                mFinalLatLng = new LatLng(Lat, Log);
                binding.currentPosition.setText(string);
//                binding.tvAddressName.setText("当前位置："+string);
            }

            @Override
            public void onRegeocodeSearched(Double Lat, Double Log, String string) {
                super.onRegeocodeSearched(Lat,Log,string);
                binding.currentPosition.setText(string);
//                binding.tvAddressName.setText("当前位置："+string);
            }

            @Override
            public void getPoiItems(List<PoiItem> poiItemList) {
                super.getPoiItems(poiItemList);
                setPoiSearchOption(poiItemList);
            }
        });
        binding.mMapView.setMapClick();
        membermapsearchadapter = new MemberMapSearchAdapter(this,null);
        membermapsearchadapter.setOnItemClick(new AdapterOnItemClick<PoiItem>() {
            @Override
            public void onItemClick(PoiItem poiItem, int position) {
                isHandSetting = true;
                binding.searchList.setVisibility(View.GONE);
                binding.searchAddress.setText(poiItem.toString());
                String address = poiItem.getProvinceName() + poiItem.getCityName() + poiItem.getAdName() + poiItem.getSnippet();
                binding.currentPosition.setText(address);
                LatLng latLng = new LatLng(poiItem.getLatLonPoint().getLatitude(),poiItem.getLatLonPoint().getLongitude());
                binding.mMapView.zoomToSpan(latLng);
                mFinalLatLng = new LatLng(latLng.latitude,latLng.longitude);
                KeyboardUtils.hideSoftInput(binding.searchAddress);
            }
        });
    }

    public void showMarkerView(int pos,String title) {
        PoiItem poiItem = null;
        if (binding.mMapView.getPoiItem(title) != null){
            poiItem = binding.mMapView.getPoiItem(title);
        }else{
            poiItem = binding.mMapView.getPoiItems().get(pos);
        }
        mFinalLatLng = new LatLng(poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude());
//        binding.mMapView.setMarkerIcon(pos,true);
        String address = poiItem.getProvinceName() + poiItem.getCityName() + poiItem.getAdName() + poiItem.getSnippet();
        binding.currentPosition.setText(address);
    }

    private boolean isSearchTextValid() {
        if (TextUtils.isEmpty(searchText)) {
            MToast.showToast(this, "请输入地址");
            return false;
        }
        return true;
    }

    /**
     * PoiCiySearchOption 设置检索属性
     * city 检索城市
     * keyword 检索内容关键字
     * pageNum 分页页码
     */
    private void setPoiSearchOption(List<PoiItem> poiItemList) {
        isHandSetting = false;
        if (poiItemList != null && poiItemList.size() > 0) {
            binding.searchList.setVisibility(View.VISIBLE);
            membermapsearchadapter.setDatas(poiItemList);
            binding.searchList.setAdapter(membermapsearchadapter);
        }else {
            binding.searchList.setVisibility(View.GONE);
            membermapsearchadapter.setDatas(new ArrayList<>());
        }
        membermapsearchadapter.notifyDataSetChanged();
    }

    private void initPoiSearch() {
        double latitude = 0;
        double longtitude = 0;
        if (getIntent().hasExtra(LATITUDE)) {
            latitude = getIntent().getDoubleExtra(LATITUDE, 0);

        }
        if (getIntent().hasExtra(LONGTITUDE)) {
            longtitude = getIntent().getDoubleExtra(LONGTITUDE, 0);
        }
        if (latitude !=0 && longtitude != 0){
            mFinalLatLng = new LatLng(latitude, longtitude);
            binding.mMapView.setMyLocation(latitude,longtitude,0);
            if (TextUtils.isEmpty(getIntent().getStringExtra(CITY))){
                binding.mMapView.getLatLotExtra(latitude,longtitude);
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.searchPosition) {
            searchText = binding.searchAddress.getText().toString().trim();
            if (isSearchTextValid()) {
//                    KeyboardUtils.hideSoftInput(binding.searchAddress);
                binding.mMapView.setPoiSearch(searchText, "");
            }
        } else if (id == R.id.commitButton) {
            Intent intent = new Intent();
            intent.putExtra(CURRENT_POSITION, binding.currentPosition.getText().toString());
            intent.putExtra(LATITUDE, mFinalLatLng.latitude);
            intent.putExtra(LONGTITUDE, mFinalLatLng.longitude);
            if (getIntent().getIntExtra(IS_FRAGMENT, 0) != 0) {
                intent.putExtra(IS_FRAGMENT, getIntent().getIntExtra(IS_FRAGMENT, 0));
            }
            setResult(RESULT_OK, intent);
            finish();
        } else if (id == R.id.iv_back) {
            KeyboardUtils.hideSoftInput(binding.searchAddress);
            finish();
        } else if (id == R.id.ll_buttom_layout) {// 空实现，为了不响应下层布局的地图时间监听
        } else if (id == R.id.tv_search_delete) {
            isSearching = false;
            binding.searchAddress.setText("");
            searchText = "";
            binding.searchList.setVisibility(View.GONE);
        }
    }

}
